# This is a sample Python script
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import time
from nicegui import ui, app
from uuid import uuid4
import asyncio
import hashlib
from orm import manager
from pages.personal_information import *
from pages.question_group import *
from pages.user_group import *
from tools import loginout

from pages.page_structure import init_page

app.add_static_files('/img', 'img')
app.add_static_files('/images', 'images')


async def async_try_login():
    succ, res = loginout.try_login(manager)
    ui.notify(res)


async def async_try_register():
    succ, res = loginout.try_register(manager)
    ui.notify(res)


async def logout():
    app.storage.user['login'] = 'False'
    ui.open('/')


async def deleteQues(ques_id):
    ques = manager.get_question_by_id(ques_id)
    quesjson = json.loads(ques.content)
    content = quesjson["content"]
    print(content)
    sensitive_word = manager.get_sensitive_words()
    for item in sensitive_word:
        content = content.replace(item.word, 'x')
    quesjson["content"] = content
    json1 = json.dumps(quesjson)

    testjson = json.loads(json1)
    print(testjson['content'])
    manager.update_senstive_ques(ques_id, json1)
    ui.open("/sensitive_questions")


number = [1]


@ui.page("/login")
def login_page():
    ui.query('body').classes('bg-gradient-to-br from-blue-200 to-purple-200')
    with ui.row().classes('mx-auto'):
        ui.image('/img/StarrySky_Logo.png').classes('w-12 h-12 py-8 px-8')
        ui.label("星汉 Starry Sky").classes('tracking-wide font-serif font-bold text-4xl py-8 px-8 text-black italic')
    with ui.card().classes("mx-auto my-auto h-96 w-96 bg-gradient-to-br from-purple-100 to-blue-100"):
        ui.label("Shared Exercise Platform").classes('mx-auto tracking-wide text-2xl text-black')
        ui.label("登录 Log In:").classes('mx-auto tracking-wide text-2xl text-black')
        with ui.column().classes("mx-auto my-auto"):
            with ui.row():
                ui.icon('person', color='text-indigo-400')
                ui.input(label="用户名 Username").bind_value_to(app.storage.browser, 'input_username')
            with ui.row():
                ui.icon('password', color='text-indigo-400')
                ui.input(label="密码 Password", password=True).bind_value_to(app.storage.browser, 'input_password')
            with ui.row().classes("mx-auto"):
                ui.button("登录 Log  In", on_click=async_try_login, color='text-indigo-700', icon='login') \
                    .classes('mx-auto bg-gradient-to-br from-purple-300 to-blue-300')
                ui.button("返回 Back   ", on_click=lambda: ui.open("/"), color='text-indigo-700', icon='logout') \
                    .classes('mx-auto bg-gradient-to-br from-purple-300 to-blue-300')


@ui.page("/register")
def register_page():
    app.storage.user['count'] = app.storage.user.get('count', 0) + 1
    ui.query('body').classes('bg-gradient-to-br from-blue-200 to-purple-200')
    with ui.row().classes('mx-auto'):
        ui.image('/img/StarrySky_Logo.png').classes('w-12 h-12 py-8 px-8')
        ui.label("星汉 Starry Sky").classes('tracking-wide font-serif font-bold text-4xl py-8 px-8 text-black italic')
    with ui.card().classes("mx-auto my-auto h-96 w-96 bg-gradient-to-br from-purple-100 to-blue-100"):
        ui.label("Shared Exercise Platform").classes('mx-auto tracking-wide text-2xl text-black')
        ui.label("注册 Sign Up:").classes('mx-auto tracking-wide text-2xl text-black')
        with ui.column().classes("mx-auto my-auto"):
            with ui.row():
                ui.icon('person', color='text-indigo-400')
                ui.input(label="用户名 Username").bind_value_to(app.storage.browser, 'input_username')
            with ui.row():
                ui.icon('password', color='text-indigo-400')
                ui.input(label="密码 Password", password=True).bind_value_to(app.storage.browser, 'input_password')
            with ui.row().classes("mx-auto"):
                ui.button("注册 Sign Up", on_click=async_try_register, color='text-indigo-700', icon='history_edu') \
                    .classes('mx-auto bg-gradient-to-br from-purple-300 to-blue-300')
                ui.button("返回 Back   ", on_click=lambda: ui.open("/"), color='text-indigo-700', icon='logout') \
                    .classes('mx-auto bg-gradient-to-br from-purple-300 to-blue-300')


@ui.page("/user")
async def user_page():
    if app.storage.user.get('login', 'False') != 'True':
        ui.button("无权限，返回主页", on_click=lambda: ui.open('/'))
        print("error")
    else:
        init_page()
        ui.image('/img/StarrySky_Cover.jpg').classes('mx-auto')
        with ui.row().classes("w-full"):
            with ui.card().classes("mx-auto h-96 grow bg-gradient-to-br from-purple-50 to-purple-50"):
                ui.label('公告').classes('mx-auto tracking-wide text-2xl text-black')
                ui.label('敬请期待') \
                    .bind_text_from(app.storage.general, "公告")
            with ui.card().classes("mx-auto h-96 grow bg-gradient-to-br from-purple-50 to-purple-50"):
                ui.label('做题记录').classes('mx-auto tracking-wide text-2xl text-black')
                history = manager.get_histroy(manager.get_user(app.storage.user['username']).id)
                with ui.scroll_area().classes('w-full'):
                    with ui.row().classes("w-full"):
                        with ui.splitter().classes("grow") as splitter:
                            with splitter.before:
                                ui.label("题目id").classes('grow')
                            with splitter.after:
                                ui.label("得分").classes("grow")
                    for his in history:
                        with ui.row().classes("w-full mt-3"):
                            with ui.splitter().classes("grow") as splitter:
                                with splitter.before:
                                    with ui.row().classes('grow'):
                                        ui.button("查看题目",color='text-indigo-700',
                                                  on_click=lambda qid = his.question_id:
                                                  question_card(manager.get_question_by_id(qid), pop=True)).classes(
                                            "bg-gradient-to-r from-blue-100 to-purple-50"
                                        )
                                        ui.label(str(his.question_id)).classes('grow')
                                with splitter.after:
                                    ui.label(str(his.score)).classes("grow")
            with ui.card().classes("mx-auto h-96 grow bg-gradient-to-br from-purple-50 to-purple-50"):
                ui.label('做推荐题目组').classes('mx-auto tracking-wide text-2xl text-black')
                recommands = manager.recommend_questiongroup(app.storage.user['username'])
                with ui.scroll_area().classes('w-full'):
                    num = 0
                    for recommandQuestionGroup in recommands:
                        if(num >= 3):
                            break
                        num+=1
                        with ui.row().classes("w-full mb-3"):
                            ui.label(recommandQuestionGroup.group_name).classes("grow text-center")
                            ui.button("查看题目组", color='text-indigo-700',
                                      on_click=lambda qid=recommandQuestionGroup.id:
                                      ui.open("/question_group/{}".format(qid))).classes(
                                "bg-gradient-to-r from-blue-100 to-purple-50"
                            )

@ui.page("/sensitive_questions")
async def sensitive_ques_page():
    init_page()
    columns = [
        {'name': 'quesId', 'label': '题目ID', 'field': 'quesId'},
        {'name': 'creatorId', 'label': '创建者ID', 'field': 'creatorId'},
        {'name': 'quesName', 'label': '题目名', 'field': 'quesName'},
        {'name': 'operation', 'label': "操作", 'field': 'operation'}
    ]
    q = manager.select_sensitive_question()
    rows = []
    with ui.card().classes('w-full bg-gradient-to-br from-purple-50 to-blue-50'):
        with ui.row().classes('w-9/12'):
            ui.label("题目ID").classes('mx-auto w-2/12')
            ui.label("创建者ID").classes('mx-auto w-2/12')
            ui.label("题目名字").classes('mx-auto w-5/12')

    for item in q:
        full_text = "问题描述: " + item.content
        with ui.card().classes('w-full bg-gradient-to-br from-purple-50 to-blue-50'):
            with ui.row().classes('w-full'):
                ui.label(str(item.id)).classes('mx-auto w-2/12')
                ui.label(str(item.creator_id.id)).classes('mx-auto w-2/12')
                ui.label(item.question_name).classes('mx-auto w-4/12')
                ui.button("查看题目", color='text-indigo-700',
                          on_click=lambda qid=item.id:
                          question_card(manager.get_question_by_id(qid), pop=True)).classes(
                    "bg-gradient-to-br from-purple-200 to-blue-200")
                ui.button("删除", on_click=lambda: deleteQues(item.id), color='text-indigo-700',
                          icon='remove').classes('bg-red-600 text-white')


with ui.column().classes("mx-auto my-auto"):
    ui.query('body').classes('bg-gradient-to-br from-blue-200 to-purple-200')
    with ui.row().classes('mx-auto'):
        ui.image('/img/StarrySky_Logo.png').classes('w-12 h-12 py-8 px-8')
        ui.label("星汉 Starry Sky").classes('tracking-wide font-serif font-bold text-4xl py-8 px-8 text-black italic')
    with ui.card().classes("mx-auto my-auto h-96 w-96 bg-gradient-to-br from-purple-100 to-blue-100"):
        ui.label("Shared Exercise Platform").classes('mx-auto tracking-wide text-2xl text-black')
        ui.label("欢迎 Welcome!").classes('mx-auto tracking-wide text-2xl text-black')
        ui.button("注册 Sign Up", on_click=lambda: ui.open("/register"), color='text-indigo-700', icon='history_edu') \
            .classes('mx-auto bg-gradient-to-br from-purple-300 to-blue-300 w-full')
        ui.button("登录 Log  In", on_click=lambda: ui.open("/login"), color='text-indigo-700', icon='login') \
            .classes('mx-auto bg-gradient-to-br from-purple-300 to-blue-300 w-full')


ui.run(storage_secret='buaa2023')
